# pip install PyJWT

import datetime
import jwt

CLAIM_TYPE = 'typ'  # 声明-类型
CLAIM_ALG = 'alg'  # 声明-加密/解密方式
CLAIM_EXP_TIME = 'exp'  # 声明-过期时间
CLAIM_NOT_BEFORE_TIME = 'nbf'  # 声明-校验时间不能在此设定时间之后
CLAIM_ISSUER = 'iss'  # 声明-发行者
CLAIM_ISSUED_AT = 'iat'  # 声明-发行时间
CLAIM_AUDIENCE = 'aud'  # 声明- 观众

secret_key = '91B13A20-15B0-4BBC-A116-F44A4E1E6EF3'  # # 密钥
timeout = 60 * 60 * 24  # 超时时间, 单位: 秒
leeway_time = 60  # 超时时间检验误差阀值, 单位: 秒
not_before = True  # 是否允许校验服务器时间在本服务器之前
issuer = 'ZYF:XM'  # 发行者信息


def encode(secret_key=secret_key, headers=None, json_encoder=None,
           timeout=timeout, **kwargs) -> bytes:
    """
    生成json web token

    :param secret_key: 签名密钥
    :param headers: token头信息
    :param json_encoder:
    :param kwargs:
    :return: jwt，字节型
    """
    utc_now = datetime.datetime.utcnow()
    payload = {
        'exp': utc_now + datetime.timedelta(seconds=timeout),
        'iat': utc_now,
        'iss': issuer,
    }
    if not_before:
        payload['nbf'] = utc_now
    payload.update(kwargs)

    return jwt.encode(payload, key=secret_key, headers=headers, json_encoder=json_encoder, algorithm='HS256')


def encode2str(secret_key=secret_key, headers=None, **kwargs):
    """
    生成json web token

    :param secret_key: 签名密钥
    :param headers: token头信息
    :param json_encoder:
    :param kwargs:
    :return:
    """
    # 1.7.1 生成jwt
    # return encode(secret_key=secret_key, headers=headers, **kwargs).decode('utf-8')

    # 2.7.0版本
    return encode(secret_key=secret_key, headers=headers, **kwargs)


def decode(token, secret_key=secret_key, **kwargs) -> tuple:
    """
    还原json web token

    :param token: json web token
    :param secret_key:
    :param kwargs:
    :return:
    """
    header = jwt.get_unverified_header(
        token if isinstance(token, bytes) else token.encode('utf-8'))
    payload = jwt.decode(
        token, secret_key, leeway=leeway_time, algorithms=['HS256'], **kwargs)

    # jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
    return header, payload


if __name__ == '__main__':
    # jwt_data['user_id'] = "qianyu"
    user_id = 'qianyu'
    c = encode2str(**{"user_id": user_id})
    print(c)

    # print(decode(c))
    # print('张俊'.encode('utf-8').decode('utf-8'))
